import time
import os
from util.Config import *
from util.ErrorCode import *
from util.LoggerUtil import *
from util.FieldiagUtil import *

class FieldiagMain:

    def __init__(self):
        self.logger = LoggerUtil('main').logger
        # self.util = UfidaUtil(self.logger)
        self.InitConfig()

    # 主程序主口，开始干 go go go....
    def Run_Fieldiag(self):
        try:
            # sn = '2106183903X2R5000012' #os.popen("sudo dmidecode -s baseboard-serial-number").read().strip()
            sn = os.popen("sudo dmidecode -s baseboard-serial-number").read().strip()
            print("sn=", sn)

            logFile = Config['Sys']['logDir']+"run.log"
            print("logFile="+logFile, '====')

            while not os.path.exists(logFile):
                time.sleep(60)  # 等待60秒

            # 打开文件并读取内容
            with open(logFile, 'r') as file:
                lines = file.readlines()

            # 初始化结果变量
            final_result = None

            # 遍历文件内容，寻找Final Result行
            for line in lines:
                if line.startswith('Final Result:'):
                    final_result = line.strip().split(':')[1].strip()
                    break

            # 输出结果
            if final_result:
                print(f"Final Result: {final_result}")
            else:
                print("Final Result not found in the file.")



            url = Config['Api']['log_receive'];
            key = Config['Api']['key'];

            # Header请求参数
            headers = {
                'key': key
            }

            # # Body请求参数（form-data）
            # files = {
            #     'sn': ('sn', sn), 
            #     'compress_file': ('compress_file', open(logFile, 'rb')),
            #     'receive_status': ('receive_status', final_result),
            #     'log_file': ('log_file', open(logFile, 'rb'))
            # }

            # 正确的Body参数设置
            data = {
                'sn': sn,
                'receive_status': final_result
            }
            files = {
                'compress_file': open(logFile, 'rb'),
                'log_file': open(logFile, 'rb')
            }

            # 发送POST请求
            response = requests.post(url, headers=headers, data=data, files=files)

            # 处理响应
            print(response.status_code)
            print(response.text)
            

            self.logger.info("Main Task Finish: >>> Success")
        except Exception as e:
            self.logger.error("Main Task Error: >>> " + str(e))

    # 初始化配置信息 InitConfig
    def InitConfig(self):
        pass
                    
# 主方法
if __name__ == "__main__":
    # 为了保活 这里来个死循环。。
    # while True:
    try:
        FieldiagMain().Run_Fieldiag()
        # 每分钟同步一次全局任务
        # time.sleep(300)
    except Exception as e:
        print("Main Error: >>> ", e)

        
